#include <stdint.h>
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>

#include "vicl.h"

int validate_ip_address(const char *ip_str, uint8_t* ip_array)
{
        unsigned int n1,n2,n3,n4;

        if(sscanf(ip_str,"%u.%u.%u.%u", &n1, &n2, &n3, &n4) != 4) return -1;
        if((n1 > 255) || (n2 > 255) || (n3 > 255) || (n4 > 255)) return -1;
        
        ip_array[0] = (uint8_t)n1;
        ip_array[1] = (uint8_t)n2;
        ip_array[2] = (uint8_t)n3;
        ip_array[3] = (uint8_t)n4;
        
        return 0;
}

int validate_hostname(const char* hostname)
{
    bool ssl;
    const char *ipaddress;
    char* port;
    uintptr_t ipsize;
    int portint;

    // examine the URL prefix
    if(!memcmp("https://", hostname, 8))
        ssl = true;
    else if(!memcmp("http://", hostname, 7))
        ssl = false;
    else
    {
        VICL_ERROR("Invalid hostname prefix\n");
        return -1;
    }

    // examine the IP address
    ipaddress = hostname + (ssl ? 8 : 7);
    if(!(port = strchr(ipaddress, ':')))
    {
        VICL_ERROR("Invalid IP address format\n");
        return -1;
    }

    ipsize = (uintptr_t)port - (uintptr_t)ipaddress;
    port++;
    
    uint8_t ipint[4];
    if(validate_ip_address(ipaddress, ipint) == -1)
    {
        VICL_ERROR("Invalid IP address format\n");
        return -1;
    }

    
    if(sscanf(port, "%u", &portint) != 1)
    {
        VICL_ERROR("Invalid hostname format\n");
        return -1;
    }
    
    return 0;
}
